package com.example.springboot.controller;

import com.example.springboot.config.JwtTokenUtil;
import com.example.springboot.dto.AdminRequestDTO;
import com.example.springboot.entity.Admin;
import com.example.springboot.service.AdminService;

import com.example.springboot.service.OSSService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private OSSService ossService;

    private static final String DEFAULT_AVATAR_URL = "https://example.com/default-avatar.jpg"; // 默认头像地址
    @GetMapping("/ssss")
    public String ssss(){
        return "ssss";
    }
    // 获取所有管理员列表
    @GetMapping("/getAllAdmins")
    @ApiOperation("获取所有管理员列表")
    public ResponseEntity<?> getAllAdmins(
            @RequestHeader("Authorization") String token) {
        try {
            // 从 token 中解析当前管理员用户名
            String currentAdminUsername = jwtTokenUtil.getUsernameFromToken(token);

            if (currentAdminUsername == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
            }

            // 调用 AuthService 获取所有管理员信息
            List<Admin> admins = adminService.getAllAdmins();

            // 返回管理员列表
            return ResponseEntity.ok(admins);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }

    // 查找管理员
    @GetMapping("/getAdminByUsername")
    @ApiOperation("查找管理员")
    public ResponseEntity<?> getAdminByUsername(@RequestParam String username) {
        try {
            Admin admin = adminService.getAdminByUsername(username);
            if (admin == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("管理员不存在");
            }
            return ResponseEntity.ok(admin);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误: " + e.getMessage());
        }
    }

        /**
         * 更新管理员信息（支持头像上传）
         *
         * @param token        Authorization token
         * @param adminRequest 更新信息 DTO
         * @param file         头像文件（选填）
         * @return 更新结果
         */
        @PostMapping("/updateAdmin")
        @ApiOperation("更新管理员信息")
        public ResponseEntity<?> updateAdmin(
                @RequestHeader("Authorization") String token,
                @RequestPart("adminRequest") AdminRequestDTO adminRequest,
                @RequestPart(value = "file", required = false) MultipartFile file) {
            try {
                // 从 token 中解析当前管理员用户名
                String currentAdminUsername = jwtTokenUtil.getUsernameFromToken(token);

                if (currentAdminUsername == null) {
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
                }

                // 验证请求中的必填字段是否完整
                if (adminRequest.getUsername() == null || adminRequest.getUsername().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("用户名不能为空");
                }
                if (adminRequest.getPasswordHash() == null || adminRequest.getPasswordHash().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("密码不能为空");
                }
                if (adminRequest.getRegion() == null || adminRequest.getRegion().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("地区不能为空");
                }

                // 上传头像文件，如果提供了头像文件
                if (file != null && !file.isEmpty()) {
                    String avatarUrl = ossService.uploadFile(file, currentAdminUsername);
                    adminRequest.setAvatarUrl(avatarUrl);
                } else if (adminRequest.getAvatarUrl() == null || adminRequest.getAvatarUrl().trim().isEmpty()) {
                    adminRequest.setAvatarUrl(DEFAULT_AVATAR_URL);
                }

                // 更新管理员信息
                Admin updatedAdmin = new Admin();
                updatedAdmin.setUsername(adminRequest.getUsername());
                updatedAdmin.setPasswordHash(adminRequest.getPasswordHash());
                updatedAdmin.setRegion(adminRequest.getRegion());
                updatedAdmin.setAvatarUrl(adminRequest.getAvatarUrl());

                // 调用服务逻辑更新管理员
                String result = adminService.updateAdmin(updatedAdmin);

                return ResponseEntity.ok(result);
            } catch (IllegalArgumentException e) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
            }
        }

        /**
         * 添加管理员（支持头像上传）
         *
         * @param token        Authorization token
         * @param adminRequest 添加管理员 DTO
         * @param file         头像文件（选填）
         * @return 添加结果
         */
        @PostMapping("/addAdmin")
        @ApiOperation("添加管理员")
        public ResponseEntity<?> addAdmin(
                @RequestHeader("Authorization") String token,
                @RequestPart("adminRequest") AdminRequestDTO adminRequest,
                @RequestPart(value = "file", required = false) MultipartFile file) {
            try {
                // 从 token 中解析当前管理员用户名
                String currentAdminUsername = jwtTokenUtil.getUsernameFromToken(token);

                if (currentAdminUsername == null) {
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
                }

                // 验证请求中的必填字段是否完整
                if (adminRequest.getUsername() == null || adminRequest.getUsername().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("用户名不能为空");
                }
                if (adminRequest.getPasswordHash() == null || adminRequest.getPasswordHash().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("密码不能为空");
                }
                if (adminRequest.getRegion() == null || adminRequest.getRegion().trim().isEmpty()) {
                    return ResponseEntity.badRequest().body("地区不能为空");
                }

                // 上传头像文件，如果提供了头像文件
                if (file != null && !file.isEmpty()) {
                    String avatarUrl = ossService.uploadFile(file, currentAdminUsername);
                    adminRequest.setAvatarUrl(avatarUrl);
                } else if (adminRequest.getAvatarUrl() == null || adminRequest.getAvatarUrl().trim().isEmpty()) {
                    adminRequest.setAvatarUrl(DEFAULT_AVATAR_URL);
                }

                // 创建新管理员对象
                Admin newAdmin = new Admin();
                newAdmin.setUsername(adminRequest.getUsername());
                newAdmin.setPasswordHash(adminRequest.getPasswordHash());
                newAdmin.setRegion(adminRequest.getRegion());
                newAdmin.setAvatarUrl(adminRequest.getAvatarUrl());

                // 调用服务逻辑添加管理员
                adminService.addAdmin(currentAdminUsername, newAdmin);

                return ResponseEntity.ok("管理员添加成功");
            } catch (IllegalArgumentException e) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getMessage());
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
            }
        }



    // 删除管理员
    @DeleteMapping("/deleteAdmin")
    @ApiOperation("删除管理员")
    public ResponseEntity<?> deleteAdmin(
            @RequestHeader("Authorization") String token,
            @RequestParam String username) {
        try {
            // 从 token 中解析当前管理员用户名
            String currentAdminUsername = jwtTokenUtil.getUsernameFromToken(token);

            if (currentAdminUsername == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
            }

            // 验证请求中的用户名是否完整
            if (username == null || username.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("用户名不能为空");
            }

            // 调用 AuthService 删除管理员逻辑
            String result = adminService.deleteAdmin(username);

            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }
    /**
     * 上传管理员头像
     */
    @PostMapping("/uploadAvatar")
    public ResponseEntity<?> uploadAvatar(
            HttpServletRequest request,
            @RequestParam("file") MultipartFile file) {
        try {
            String currentAdminUsername = (String) request.getAttribute("username");
            if (currentAdminUsername == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token 或未通过认证");
            }

            String fileUrl = ossService.uploadFile(file, currentAdminUsername);
            return ResponseEntity.ok("头像上传成功，访问地址: " + fileUrl);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }

    /**
     * 修改当前登录管理员的用户名
     */
    @PostMapping("/updateCurrentUsername")
    @ApiOperation("修改当前登录管理员的用户名")
    public ResponseEntity<?> updateCurrentUsername(
            HttpServletRequest request,
            @RequestParam String newUsername) {
        try {
            String currentAdminUsername = (String) request.getAttribute("username");
            if (currentAdminUsername == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token 或未通过认证");
            }
            if (newUsername == null || newUsername.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("新用户名不能为空");
            }

            // 更新用户名
            String result = adminService.updateCurrentUsername(currentAdminUsername, newUsername);

            // 获取更新后的管理员信息
            Admin updatedAdmin = adminService.getAdminByUsername(newUsername);
            if (updatedAdmin == null) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新后无法找到管理员");
            }

            // 生成新的 token，使用现有方法
            String role = (String) request.getAttribute("role"); // 从现有 token 中获取 role
            String newToken = jwtTokenUtil.generateToken(newUsername, role);

            // 返回结果和新 token
            Map<String, String> response = new HashMap<>();
            response.put("message", result);
            response.put("token", newToken);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }

    /**
     * 发送管理员密码修改验证码
     */
    @PostMapping("/sendAdminPasswordCode")
    public ResponseEntity<?> sendAdminPasswordCode(HttpServletRequest request) {
        try {
            String currentAdminUsername = (String) request.getAttribute("username");
            System.out.println("当前管理员用户名: " + currentAdminUsername); // 日志
            if (currentAdminUsername == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token 或未通过认证");
            }
            String resetCode = adminService.sendAdminPasswordResetCode(currentAdminUsername);
            return ResponseEntity.ok("验证码已生成: " + resetCode);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误: " + e.getMessage());
        }
    }

    /**
     * 修改当前登录管理员的密码（使用验证码验证）
     */
    @PostMapping("/updateCurrentPassword")
    @ApiOperation("修改当前登录管理员的密码")
    public ResponseEntity<?> updateCurrentPassword(
            HttpServletRequest request,
            @RequestParam String verificationCode,
            @RequestParam String newPassword) {
        try {
            String currentAdminUsername = (String) request.getAttribute("username");
            if (currentAdminUsername == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token 或未通过认证");
            }
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("新密码不能为空");
            }

            String result = adminService.updateCurrentPassword(currentAdminUsername, verificationCode, newPassword);
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }
}
